package com.rapida.app;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.File;

/**
 * Created by mm on 15-1-16.
 */
public class StorageManager {
    private static final String TAG = "StorageManager";

    public static final long UNAVAILABLE = -1L;
    public static final long PREPARING = -2L;
    public static final long UNKNOWN_SIZE = -3L;
    public static final long LOW_STORAGE_THRESHOLD = 50000000;

    private String DIRECTORY = Environment.getExternalStorageDirectory().toString();
    private static StorageManager sStorage;

    private StorageManager() {
    }

    public static StorageManager getStorage() {
        if (sStorage == null) {
            sStorage = new StorageManager();
        }
        return sStorage;
    }

    public void setStorage(String path) {
        DIRECTORY = path;
    }

    public String generateDirectory() {
        return new File(DIRECTORY).toString();
    }

    public long getAvailableSpace() {
        String state = Environment.getExternalStorageState();
        Log.d(TAG, "External storage state=" + state);
        if (Environment.MEDIA_CHECKING.equals(state)) {
            return PREPARING;
        }
        if (!Environment.MEDIA_MOUNTED.equals(state)) {
            return UNAVAILABLE;
        }

        File dir = new File(generateDirectory());
        dir.mkdirs();
        if (!dir.isDirectory() || !dir.canWrite()) {
            return UNAVAILABLE;
        }

        try {
            StatFs stat = new StatFs(generateDirectory());
            return stat.getAvailableBlocks() * (long) stat.getBlockSize();
        } catch (Exception e) {
            Log.i(TAG, "Fail to access external storage", e);
        }
        return UNKNOWN_SIZE;
    }

    public boolean isFullSpace() {
        long space = getAvailableSpace();
        if (space == UNAVAILABLE || space == PREPARING || space == UNKNOWN_SIZE) {
            return true;
        }
        return getAvailableSpace() < LOW_STORAGE_THRESHOLD;
    }
}
